class NutritionData {
  final String name;
  final String type;
  final double calories;
  final double protein;
  final double fat;
  final double carbs;
  final double fiber;
  // 其他营养素...

  NutritionData({
    required this.name,
    required this.type,
    required this.calories,
    required this.protein,
    required this.fat,
    required this.carbs,
    required this.fiber,
  });

  factory NutritionData.fromJson(Map<String, dynamic> json) {
    return NutritionData(
      name: json['name'] ?? '未知食品',
      type: json['type'] ?? '未知',
      calories: _parseDouble(json['rl']),
      protein: _parseDouble(json['dbz']),
      fat: _parseDouble(json['zf']),
      carbs: _parseDouble(json['shhf']),
      fiber: _parseDouble(json['ssxw']),
    );
  }

  static double _parseDouble(dynamic value) {
    if (value == null) return 0.0;
    if (value is num) return value.toDouble();
    try {
      return double.parse(value.toString());
    } catch (_) {
      return 0.0;
    }
  }
}
